﻿using Max.PH5_2010A.Shopping.Domain;
using Max.PH5_2010A.Shopping.DTO;
using Max.PH5_2010A.Shopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;

namespace Max.PH5_2010A.Shopping.API.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("product")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        IBrandService _brandService;
        ICategorService _categoryService;
        IProductSpuService _productSpuService;
        IProductSkuService _productSkuService;
        IProductSkuImageService _productSkuImageService;

        IProductCategorySpecService _productCategorySpecService;
        IProductCategorySpecValueService _productCategorySpecValueService;
        IProductSpecService _productSpecService;

        public ProductController(IBrandService brandService, ICategorService categoryService, IProductSpuService productSpuService, IProductSkuService productSkuService, IProductSkuImageService productSkuImageService, IProductCategorySpecService productCategorySpecService, IProductCategorySpecValueService productCategorySpecValueService, IProductSpecService productSpecService)
        {
            _brandService = brandService;
            _categoryService = categoryService;
            _productSpuService = productSpuService;
            _productSkuService = productSkuService;
            _productSkuImageService = productSkuImageService;
            _productCategorySpecService = productCategorySpecService;
            _productCategorySpecValueService = productCategorySpecValueService;
            _productSpecService = productSpecService;
        }

        /// <summary>
        /// 产品列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get(string? categoryId,string? brandId,
            string? sortName="id",string? sortValue="desc",
            int pageIndex = 1, int pageSize = 4)
        {
            //API中三件事
            if (pageIndex <= 0) pageIndex = 1;
            if (pageSize <= 0) pageSize = 4;

            if(string.IsNullOrEmpty(sortValue)) sortValue = "desc";
            if(string.IsNullOrEmpty(sortName)) sortName = "id";

            /*
             * 前台调用这个接口，需要获取三个数据
             * 1、分类数据
             * 2、品牌数据
             * 3、商品数据
             * 
             * **/

            ResponseResultDto dto = new();

            //分类数据
            var categories = _categoryService.GetRecursionCategory();

            //品牌数据            
            var brands = _brandService.Select();

            //产品数据
            var products = from a in _productSpuService.Select()
                           where a.BrandID.ToString().Contains(brandId ?? "") 
                                && a.CategoryID.ToString().Contains(categoryId ?? "")
                           select new
                           {
                               spuid = a.Id,
                               categoryId = a.CategoryID,
                               a.Name,
                               coverImagePath = $"http://localhost:5162/{a.CoverImagePath}",
                               sku = _productSkuService.Select().Where(x => x.SPUID == a.Id).Select(x => new { x.SalePrice,x.Id }).FirstOrDefault(),
                               saleNumber = 0,
                               a.CreatedTime
                           };


            //System.Linq.Expressions.Expression<Func<ProductSPUModel, object>> express = x => x.Name;
            //express.And()

            //排序（对结果集进行排序操作）
            switch (sortName.ToLower())
            {
                case "name":
                    //Func<ProductSPUModel, string> sort = x => x.Name;
                    //_productSpuService.Select(sort, true);

                    if (sortValue.ToLower().Equals("desc"))
                    {
                        products = products.OrderByDescending(x => x.Name);
                    }
                    else
                    {
                        products = products.OrderBy(x => x.Name);
                    }
                    break;
                case "date":
                    if (sortValue.ToLower().Equals("desc"))
                    {
                        products = products.OrderByDescending(x => x.CreatedTime);
                    }
                    else
                    {
                        products = products.OrderBy(x => x.CreatedTime);
                    }
                    break;
                default:
                    if (sortValue.ToLower().Equals("desc"))
                    {
                        products = products.OrderByDescending(x => x.spuid);
                    }
                    else
                    {
                        products = products.OrderBy(x => x.spuid);
                    }
                    break;
            }


            //if (sortName.ToLower().Equals("name"))
            //{
            //    if (sortValue.ToLower().Equals("desc"))
            //    {
            //        products = products.OrderByDescending(x => x.Name);
            //    }
            //    else
            //    {
            //        products = products.OrderBy(x => x.Name);
            //    }
            //}


            var total = products.Count();
            products = products.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            dto.Data = new { categories, brands, products, total };

            return Ok(dto);
        }

        /// <summary>
        /// 根据SKUID获取SKU的详细信息
        /// </summary>
        /// <param name="skuId"></param>
        /// <returns></returns>
        [HttpGet("byid")]
        public IActionResult GetDataBySkuId(string skuId,string categoryId)
        {
            if(string.IsNullOrEmpty(skuId))
            {
                return BadRequest();
            }
            ResponseResultDto dto = new();


            #region 2023/4/29 根据这款spu的分类id,去找到这个分类的规格及规格值

            //这个分类有多少个规格：找分类规格表
            var _categorySpec = _productCategorySpecService.Select().Where(x => x.CategoryId.ToString().Equals(categoryId));

            //找这个分类规格下面，每个规格对应的值：找分类规格值表
           var _categorySpecValues =  from a in _categorySpec
            select new
            {
                //a.SpecId
                SpecName = _productSpecService.Select().Where(x=>x.Id == a.SpecId).FirstOrDefault().Name,
                SpecValues = _productCategorySpecValueService.Select().Where(x => x.CategorySpecId == a.Id).ToList()
            };


            #endregion

            //var m = _productSkuService.Select().Where(x => x.Id.ToString().Equals(skuId)).FirstOrDefault();

            var m = from a in _productSkuService.Select()
                   where a.Id == new Guid(skuId)
            select new
            {
                a.Id,
                a.SalePrice,
                a.MarketPrice,
                a.Name,
                a.Specs,
                images = _productSkuImageService.Select().Where(x => x.SKUID == a.Id).OrderBy(x => x.Sort).ToList()
            };

            dto.Data = new { skuData = m.FirstOrDefault(),  specValue = _categorySpecValues };

            return Ok(dto);
        }


    }
}
